package com.eoner.baselibrary.permission;

import android.content.Context;
import android.hardware.Camera;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Build;
import java.lang.reflect.Field;
/**
* android 6.0 以下判断音视频权限
* */
public class AVLOLLIPOPPermission {

    /**
     * 通过尝试打开相机的方式判断有无拍照权限（在6.0以下使用拥有root权限的管理软件可以管理权限）
     * 判断是否有摄像头权限
     * @return
     */
    public static boolean cameraIsCanUse() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return true;
        }
        //如果大于6.0且是小米手机直接返回true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                && (Build.MANUFACTURER.equals("xiaomi")
                || Build.MANUFACTURER.equals("Xiaomi"))) {
            return true;
        }
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.MANUFACTURER.contains("360"))) {
            return true;
        }
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.MANUFACTURER.contains("QIKU"))) {
            return true;
        }
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.MANUFACTURER.contains("qiku"))) {
            return true;
        }
        if (Build.MANUFACTURER.toLowerCase().contains("smartisan")) {
            return true;
        }

        if (Build.MANUFACTURER.toLowerCase().contains("moto")) {
            return true;
        }
        boolean isCanUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            //针对魅族
            Camera.Parameters mParameters = mCamera.getParameters();
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            isCanUse = false;
        }

        if (Build.MANUFACTURER.equals( "vivo")) {
            try {
                //针对vivo
                Field fieldPassword = mCamera.getClass().getDeclaredField("mHasPermission");
                fieldPassword.setAccessible(true);
                isCanUse = (boolean) fieldPassword.get(mCamera);
            } catch (Exception e) {
                isCanUse = true;
            }
        }

        if (mCamera != null) {
            try {
                mCamera.release();
            } catch (Exception e) {
                e.printStackTrace();
                return isCanUse;
            }
        }
        return isCanUse;
    }

    /**
     * 判断是否有录音权限
     * @return
     */
    public static boolean checkRecorderPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return true;
        }
        if (Build.MANUFACTURER.toLowerCase().contains("smartisan")) {
            return true;
        }
        //如果大于6.0且是小米手机直接返回true
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.MANUFACTURER.equals("xiaomi"))
                || Build.MANUFACTURER.equals("Xiaomi")) {
            return true;
        }
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.MANUFACTURER.contains("360"))) {
            return true;
        }
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.MANUFACTURER.contains("QIKU"))) {
            return true;
        }
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.MANUFACTURER.contains("qiku"))) {
            return true;
        }
        if (Build.MANUFACTURER.toLowerCase().contains("moto")) {
            return true;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return chackAudioOldPermission();
        } else {
            return checkAudioPermission();
        }
    }
    private static boolean chackAudioOldPermission() {
        // 音频获取源
        int audioSource = MediaRecorder.AudioSource.MIC;
        // 设置音频采样率，44100是目前的标准，但是某些设备仍然支持22050，16000，11025
        int sampleRateInHz = 44100;
        // 设置音频的录制的声道CHANNEL_IN_STEREO为双声道，CHANNEL_CONFIGURATION_MONO为单声道
        int channelConfig = AudioFormat.CHANNEL_IN_STEREO;
        // 音频数据格式:PCM 16位每个样本。保证设备支持。PCM 8位每个样本。不一定能得到设备支持。
        int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
        // 缓冲区字节大小
        int bufferSizeInBytes = 0;
        bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz,
                channelConfig, audioFormat);

        AudioRecord audioRecord = null;
        try {
            audioRecord =  new AudioRecord(audioSource, sampleRateInHz,
                    channelConfig, audioFormat, bufferSizeInBytes);
            //开始录制音频
            try{
                // 防止某些手机崩溃，例如联想
                try {
                    audioRecord.startRecording();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }
            } catch (IllegalStateException e){
                e.printStackTrace();
            }

            /**
             * 根据开始录音判断是否有录音权限
             */
            if (audioRecord != null) {
                if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
//            context.startActivity(new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS));
                    return false;
                }
                audioRecord.stop();
                audioRecord.release();
                audioRecord = null;

                return true;
            } else {
                return true;
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();
                audioRecord = null;
            }
        }

        return true;
    }
    private static boolean checkAudioPermission() {
        // 音频获取源
        int audioSource = MediaRecorder.AudioSource.MIC;
        // 设置音频采样率，44100是目前的标准，但是某些设备仍然支持22050，16000，11025
        int sampleRateInHz = 44100;
        // 设置音频的录制的声道CHANNEL_IN_STEREO为双声道，CHANNEL_CONFIGURATION_MONO为单声道
        int channelConfig = AudioFormat.CHANNEL_IN_STEREO;
        // 音频数据格式:PCM 16位每个样本。保证设备支持。PCM 8位每个样本。不一定能得到设备支持。
        int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
        // 缓冲区字节大小
        int bufferSizeInBytes = 0;
        bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz,
                channelConfig, audioFormat);
        try {
            AudioRecord audioRecord =  new AudioRecord(audioSource, sampleRateInHz,
                    channelConfig, audioFormat, bufferSizeInBytes);
            //开始录制音频
            try {
                // 防止某些手机崩溃，例如联想
                audioRecord.startRecording();
            } catch (IllegalStateException e){
                e.printStackTrace();
//            AVLogUtils.e(TAG, Log.getStackTraceString(e));
            }
            /**
             * 根据开始录音判断是否有录音权限
             */
            if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING
                    && audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_STOPPED) {
//            AVLogUtils.e(TAG, "audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING : " + audioRecord.getRecordingState());
                return false;
            }

            if (audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_STOPPED) {
                //如果短时间内频繁检测，会造成audioRecord还未销毁完成，此时检测会返回RECORDSTATE_STOPPED状态，再去read，会读到0的size，所以此时默认权限通过
                return true;
            }

            byte[] bytes = new byte[1024];
            int readSize = audioRecord.read(bytes, 0, 1024);
            if (readSize == AudioRecord.ERROR_INVALID_OPERATION || readSize <= 0) {
//            AVLogUtils.e(TAG, "readSize illegal : " + readSize);
                return false;
            }
            audioRecord.stop();
            audioRecord.release();
            audioRecord = null;
        } catch (IllegalArgumentException i) {
            i.printStackTrace();
        }
        return true;
    }

}
